package com.fastone.ww.generatefile.controller;

import com.fastone.ww.generatefile.exception.ApiException;
import com.fastone.ww.generatefile.file.builder.HtmlToPDFBuilder;
import com.fastone.ww.generatefile.response.ResponseResult;
import com.fastone.ww.generatefile.util.Either;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.util.Optional;


@RestController
@RequestMapping("/bill")
@Slf4j
public class GenerateController {

	@Resource
	private HtmlToPDFBuilder htmlToPDFBuilder;

	/**
	 * 生成PDF，返回s3文件路径（未实现）
	 *
	 * @param
	 * @return ResponseResult
	 */
	@PostMapping("/{salesModel}/pdf2")
	public ResponseResult pdf(
			@PathVariable String salesModel,
			@RequestParam(required = false) String filename,
			@RequestBody @Valid Object data) {
		Either<ApiException, String> either = htmlToPDFBuilder.builder(Optional.ofNullable(filename),
				salesModel, data);
		return either.fold(ResponseResult::fail, ResponseResult::success);
	}

	/**
	 * 返回文件流，直接返回文件流
	 *
	 * @return FCP, FCE, FCC
	 */
	@SneakyThrows
	@PostMapping("/{salesModel}/pdf")
	public ResponseEntity<FileSystemResource> cratepdf01(
			@PathVariable String salesModel,
			@RequestParam(required = false) String business,
			@RequestParam(required = false) String filename,
			@RequestBody @Valid Object data,
			HttpServletResponse resp
	) {
		File file = htmlToPDFBuilder.builderFile(Optional.ofNullable(filename), salesModel, data);
		return ResponseResult.export(file);
	}
}
